package cn.ghx.xboot.config.handler;

import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.TypeReference;
import org.postgresql.util.PGobject;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

@MappedJdbcTypes(JdbcType.OTHER)
public class JsonMapTypeHandler extends BaseTypeHandler<Map<String,Object>> {

    private static final PGobject jsonObject = new PGobject();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Map<String,Object> parameter, JdbcType jdbcType) throws SQLException {
        jsonObject.setType("json");
        jsonObject.setValue(JSONUtil.toJsonStr(parameter));
        ps.setObject(i, jsonObject);
    }
    // ...
    @SneakyThrows
    @Override
    public Map<String,Object> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return JSONUtil.toBean(rs.getString(columnName), new TypeReference<Map<String, Object>>(){}.getRawType(),true);
    }

    @Override
    public Map<String, Object> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return JSONUtil.toBean(rs.getString(columnIndex), new TypeReference<Map<String, Object>>(){}.getRawType(),true);
    }

    @Override
    public Map<String, Object> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return JSONUtil.toBean(cs.getString(columnIndex), new TypeReference<Map<String, Object>>(){}.getRawType(),true);
    }
}

